﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;

namespace RuneLog.GrandExchange
{
    /// <summary>
    /// Can convert items between names and IDs
    /// </summary>
    class ItemIdProvider
    {
        /// <summary>
        /// Represents the database where Item information can be retrieved from.
        /// </summary>
        private readonly SQLiteConnection db;

        /// <summary>
        /// Can perform searches on the runescape item database.
        /// </summary>
        /// <param name="file"></param>
        public ItemIdProvider(string file)
        {
            db = new SQLiteConnection("Data Source=" + file + ";Version=3;");
            db.Open();
        }

        /// <summary>
        /// Get the ID of an item by name
        /// </summary>
        /// <param name="name">The correct name of the item</param>
        /// <returns>The ID of the name that is used by Jagex</returns>
        public int GetId(string name)
        {

            var data = new SQLiteCommand("SELECT Id FROM Items WHERE Name = '" + name.Replace("'", "#$") + "';", db).ExecuteReader();
            data.Read();
            try
            {
                return data.GetInt32(0);
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// Returns a list of itemnames that pass a search filter
        /// </summary>
        /// <param name="search">The string to search for</param>
        /// <returns>A list of names</returns>
        public List<String> GetItems(string search)
        {
            var result = new List<String>();
            var data = new SQLiteCommand("SELECT Name FROM Items WHERE Name LIKE '%" + search + "%' ORDER BY Name ASC;", db).ExecuteReader();
            while (data.Read())
            {
                result.Add(data.GetString(0));
            }
            return result;
        }
    }
}
